//
//  Device.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/3/25.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyJSON
import CoreBluetooth

class Device: UIViewController,UITableViewDelegate,UITableViewDataSource {
    

    // MARK: - Attribute
    @IBOutlet weak var leftTableViewWidth: NSLayoutConstraint!
    @IBOutlet weak var rigthTableView: UITableView!
    @IBOutlet weak var leftTableView: UITableView!
    @IBOutlet weak var deviceRightTableView: UITableView!
    
    
    private var centralManager: CBCentralManager?
    private var peripheral: CBPeripheral?
    private var characteristic: CBCharacteristic?
    
    
    var _indexPath = NSIndexPath.init(row: 0, section: 0)
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshAutoNormalFooter()
    // 模拟数据
    var somAry: Array<Any>! //总
    var rightAry: Array<Any>! //right
    var rightControlAry: Array<Any>! // 设备控制列表
    @IBOutlet weak var deviceWLayout: NSLayoutConstraint!
    
    
    private lazy var isDeviceConfig: Bool =  {
        return false    //默认不是设备页
    }()
    
    // MARK: - DataSource \ Delegate
    // 区
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView.tag == 110 {
          return 1
        }else if tableView.tag == 111 {  // 数据录入页
          return 2 // 2 个分区
        }else {
           return 2
        }
      
    }
    // 高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView.tag == 110 {
          return 50 //
        }else {
            
            if indexPath.section == 0 { // 数据录入部分
                let newDic = self.rightAry![indexPath.row] as! NSDictionary
                let type = newDic["type"] as! String
                
                if type == "field" {
                    return 80
                }else if type == "circular" {
                    return 80
                }else if type == "radio"{
                    if (newDic["value"] is Array<Any>) {
                        print("是")
                        let value = newDic["value"]  as! Array<Any>
                        let  i = CGFloat(value.count/2) + 1
                        return 50 * i
                    }else {
                        // 不是就返回 50 吧
                        return 50
                    }
                }else {
                    return 50
                }
            }else {   // 控制部分
//                let newDic = self.rightControlAry![indexPath.row] as! NSDictionary
                let newDic = self.rightControlAry[indexPath.row] as! NSDictionary
                let type = newDic["type"] as! String
                if type == "field" {
                    return 80
                }else if type == "circular" {
                    return 100
                }else {
                    return 50
                }
            }
            
   
        }
    }
    // 行
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.tag == 110 {
           return self.somAry.count
        }else if tableView.tag == 111 { //数据录入
            if section == 0 {
                return (self.rightAry?.count)!
            }else {
                return self.rightControlAry.count
            }
        }else {
            if section == 0 {
                return (self.rightAry?.count)!
            }else {
                return (self.rightAry?.count)!
            }
        }
    }
    // cell 数据
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if tableView.tag == 110 {   // 左
            if indexPath.row == _indexPath.row {
                cell.isSelected = true
            }else {
                cell.isSelected = false
            }
            
            let newcell = cell as! LeftDeviceCell
            let newDic = self.somAry[indexPath.row] as! NSDictionary
            let titleStr = newDic["title"] as! String
            let iconStr = newDic["icon"] as! String
            newcell.setJson(json: ["title": titleStr, "icon" : "\(iconStr).png"])
            
        }else if tableView.tag == 111 { //右
            
            let newcell = cell as! MultiFunctionCell

            let newDic = self.rightAry![indexPath.row] as! NSDictionary
            
      
            if indexPath.section == 0 { //数据录入
                
                if indexPath.row == 0 {
                    let curDate = Date()
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                    let dateStr: String = dateFormatter.string(from: curDate)
                    
                    newDic.setValue(dateStr, forKey: "value")
                }
                let json = JSON.init(newDic)
                newcell.MFC_indexPath = indexPath
                newcell.MFC_tableTag = tableView.tag
                newcell.setJson(json: json)
            }else {   // 设备控制
                let conDic = self.rightControlAry[indexPath.row] as! NSDictionary
                newcell.MFC_indexPath = indexPath
                newcell.MFC_tableTag = tableView.tag
                let json = JSON.init(conDic)
                newcell.setJson(json: json)
            }
            
        }else {
            
//           let newcell = cell as! MultiFunctionCell
//           let newDic = self.rightAry![indexPath.row] as! NSDictionary
//
//
//            if indexPath.section == 0 { // 这里都是设备管理页面
//
//                if indexPath.row == 0 {
//                    let curDate = Date()
//                    let dateFormatter = DateFormatter()
//                    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
//                    let dateStr: String = dateFormatter.string(from: curDate)
//
//                    newDic.setValue(dateStr, forKey: "value")
//                }
//                 let json = JSON.init(newDic)
//
//                  newcell.setJson(json: json)
//            }else {   // 设备控制
//                let conDic = self.rightControlAry[indexPath.row] as! NSDictionary
//                let json = JSON.init(conDic)
//                newcell.setJson(json: json)
//            }
//
//
            
//            if indexPath.row == ((self.rightAry?.count)! - 1){
//                newcell.setJson(json: ["title": str, "type" : "circular"])
//            }else {
//                newcell.setJson(json: ["title": str, "type" : "switch"])
//            }
           
        }
    }
    // cell初始化
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView.tag == 110 {
//            let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            let cell = tableView.dequeueReusableCell(withIdentifier: "LeftDeviceCell") as! LeftDeviceCell
           tableView.separatorInset = UIEdgeInsets.zero
           tableView.layoutMargins = UIEdgeInsets.zero
            if indexPath.row == 0 {
                cell.isSelected = true
            }
            
            return cell
        }else if tableView.tag == 111 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MultiFunctionCell") as! MultiFunctionCell //MultiFunctionCell()
               cell.delegate = self
            return cell
        }else {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "MultiFunctionCell") as! MultiFunctionCell
//            var cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell") as! SwitchCell //方法二
//            let cell = Bundle.main.loadNibNamed("SwitchCell", owner: nil, options: nil)?.last as! SwitchCell
            return cell
        }
    }
    // 选择时
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.tag == 110 {
            let _cell = tableView.cellForRow(at: self._indexPath as IndexPath) as! LeftDeviceCell
            _cell.isSelected = false
            let cell = tableView.cellForRow(at: indexPath as IndexPath) as! LeftDeviceCell
            cell.isSelected = true
            _indexPath = indexPath as NSIndexPath
            let newDic = self.somAry[indexPath.row] as! NSDictionary
            self.rightAry = newDic["itemAry"] as! Array
            self.deviceRightTableView.reloadData()
            self.rigthTableView.reloadData()
            
       //     let conDic = self.rightControlAry[indexPath.row] as! NSDictionary
   
        }else {
            
        }
    }
    // 设置标题
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView.tag == 110 {
            return 0
        }else if tableView.tag == 111 {
            if section == 0 {
                return 0
            }else {
                return 30
            }
            
        }else {
            return 40
        }
    }
    
    
    // 分区的头部内容
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if tableView.tag == 110 {
            return nil
        }else if tableView.tag == 111 { //数据录入
            let sonView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
            let title = UILabel.init(frame: CGRect.init(x: 20, y: (sonView.frame.size.height / 2) - 12, width: 100.0, height: 24))
            title.textColor = UIColor.gray
            if section == 0 {
//                let imgView = UIImageView.init(frame: CGRect.init(x: 0, y: sonView.frame.size.height / 2 - 8.75, width: 17.5, height: 17.5))
//                imgView.image = UIImage.init(named: "home-icon2.png")
//                sonView.addSubview(imgView)
//                title.text = "页面设置"
                return nil
            }else {
                title.text = "设备控制"
                sonView.addSubview(title)
                return sonView
            }
          
        }else{  // 设备管理
            let sonView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 40))
            let title = UILabel.init(frame: CGRect.init(x: 20, y: (sonView.frame.size.height / 2) - 12, width: 100.0, height: 24))
            if section == 0 {
                let imgView = UIImageView.init(frame: CGRect.init(x: 0, y: sonView.frame.size.height / 2 - 8.75, width: 17.5, height: 17.5))
                imgView.image = UIImage.init(named: "home-icon2.png")
                sonView.addSubview(imgView)
                title.text = "页面设置"
            }else {
                title.text = "设备控制"
            }
            sonView.addSubview(title)
            return sonView
        }
    }
    
    
    
    
    // MARK: - setRefresh
    func setRefresh() {
        header.setRefreshingTarget(self, refreshingAction: #selector(self.headerRefresh))
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.footerRefresh))
        self.leftTableView.mj_footer = footer;
        self.rigthTableView.mj_footer = footer;
    }
    
    @objc func headerRefresh() {
        self.leftTableView.mj_header.endRefreshing()
    }
    
    @objc func footerRefresh() {
        self.leftTableView.mj_footer.endRefreshing()
    }
    // MARK: - 请求
    func requestURL() {
        
    }
    
    fileprivate func deviceConfig () {
        //self.setRefresh()
        self.setNavRightView()
        self.leftTableView.showsVerticalScrollIndicator = false
        self.rigthTableView.showsVerticalScrollIndicator = false
        self.leftTableView.separatorStyle = UITableViewCellSeparatorStyle.none //隐藏线条
        self.rigthTableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        self.rigthTableView.register(MultiFunctionCell.classForCoder(), forCellReuseIdentifier: "MultiFunctionCell")
        self.deviceRightTableView.register(MultiFunctionCell.classForCoder(), forCellReuseIdentifier: "MultiFunctionCell")
        self.leftTableView.register(LeftDeviceCell.classForCoder(), forCellReuseIdentifier: "LeftDeviceCell")
        // 读取文件
        let plistPath: String? = Bundle.main.path(forResource: "DeviceTestData", ofType: "plist")!
        let resultAry = NSMutableArray.init(contentsOfFile: plistPath!)
        self.somAry = resultAry as? Array<Any>
        let _dic: NSDictionary = resultAry![0] as! NSDictionary
        
        let dic: NSDictionary = ["value": "默认值", "type": "circular"]
        self.rightAry = _dic["itemAry"] as! Array
        
        self.rightControlAry = [["value": "special.png", "type": "circular"]]
        
//         self.rigthTableView.backgroundColor = .red
        
//        self.rightAry.append(dic)
    }
    
    func setNavRightView()  {
        let setBtn =  UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
        setBtn.setImage(UIImage(named: "configure.png"), for: .normal)
        let rightBtn = UIBarButtonItem(customView: setBtn)
        setBtn.addTarget(self, action: #selector(navRightBtn), for: UIControlEvents.touchUpInside)
        let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        negativeSpacer.width = -10
        
        navigationItem.rightBarButtonItems = [negativeSpacer, rightBtn]
    }
    
   @objc func navRightBtn() {

       self.isDeviceConfig = !(self.isDeviceConfig)
       if self.isDeviceConfig {
        
        UIView.animate(withDuration: 0.6, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.deviceWLayout.constant =  self.view.wWidth * 0.6;
            self.view.layoutIfNeeded()
        }, completion: {_ in
            self.title = "设备管理"
        })
        
       }else {
        
        UIView.animate(withDuration: 0.6, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.deviceWLayout.constant =  0;
            self.view.layoutIfNeeded()
        }, completion: {_ in
            self.title = "数据录入"
        })
        
       }
    
    }
    
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "数据录入"
        centralManager = CBCentralManager.init(delegate: self, queue: .main)
//        peripheralManager = CBPeripheralManager.init(delegate: self, queue: .main)
        
        self.deviceConfig()
//        self.rigthTableView.register(UINib.init(nibName: "SwitchCell", bundle: nil), forCellReuseIdentifier: "SwitchCell") //方法二
        
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        NetRequestTool.shareInstance.netRequest(metString: "POST", urlString: "device/types", paramsAny: nil, this: self) { (obj, message, err) in
//            print("----->\(String(describing: obj)) -----> \(String(describing: message))")
//        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension Device: MultiFunctionDelegate {
    /// 提交数据
    func buttonClick(sender: UIButton, cellIndex: IndexPath, tableTag: Int) {
//         print("3--->>",sender, self._indexPath.row)

        // 获取当前选项的数组
        let  thisAry = self.rightAry!
        var urlStr = ""
        var par = Dictionary<String, Any>()
        var keyAry =  Array<String>()
        par["id"] = ""
        if _indexPath.row == 0 { //血压
            urlStr = "user/data/blood-pressure"
            keyAry = ["systolicPressure", "diastolicPressure", "heartRate"]
        }else if _indexPath.row == 1 {
            urlStr = "user/data/weight"
            keyAry = ["type","weight"]
        }else if _indexPath.row == 2 {
            urlStr = "user/data/body-temp"
            keyAry = ["temp"]
        }else if _indexPath.row == 3 {
            urlStr = "user/data/heart-rate"
            keyAry = ["type", "heartRate"]
        }else {
           urlStr = "user/data/blood-glucose"
            keyAry = ["bloodGlucose"]
        }
            
            var i = 0
            for item in thisAry {
                var dic = item as! NSDictionary
                let str = dic["value"] as! String
                let type = dic["type"] as! String
                
                if type == "dropDown" {
//                    let date =  Date.getFromDate(dateString: str+":00")
//                    let time = Int((date?.timeIntervalSince1970)!)
//                    let timeInt =  time * 1000
                    let timeInt = getTime(date: str)
                    par["recordTime"] = timeInt
                    dic.setValue("", forKey: "value")
                }else if type == "field" {
                    
                    if i < keyAry.count {
                      par[keyAry[i]] = str
                    }
                    i += 1
                    
                    dic.setValue("", forKey: "value")
                }else if type == "radio" {
                    
                    var typeId = 1
                    if str == "餐前" {
                        typeId = 1
                    }else {
                        typeId = 2
                    }
                    if i < keyAry.count {
                    par[keyAry[i]] = typeId
                    }
                    i += 1
                    dic.setValue("", forKey: "value")
                }
            }
        
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.requestForJSON(url: urlStr, parameters: par, success: { (json) in
            //                  print("---》〉\(json)")
            if json["code"].intValue == 0 {
                self.showToast(message: "提交成功")
                par.removeAll()
                self.rigthTableView.reloadData()
                // 返回上一页
                self.navigationController?.popViewController(animated: true)
            }
        }, fail: { (code, err) in
            print("\n =>>", code, err)
        }) { }
        
//         let dicData = NSMutableDictionary(contentsOfFile: filePath)
        
        
        //提交
    }
    /// 获取时间戳
    func getTime (date: String) -> Int {
        let date =  Date.getFromDate(dateString: date+":00")
        let time = Int((date?.timeIntervalSince1970)!)
        let timeInt =  time * 1000
        
        return timeInt
    }
    
    
    
    func fieldChange(sender: UITextField, text: String, cellIndex: IndexPath, tableTag: Int) {
        let itemAry =  self.rightAry!
        var str = ""
        // 获取类型 - 比如血压下的内容
        if sender.text?.count == 1 && text == "" {
          str = ""
        }else {
          str = sender.text! + text
        }
      
        let dic = itemAry[cellIndex.row] as! NSDictionary
        dic.setValue(str, forKey: "value")
        
    }
    
    func switchChange(sender: UISwitch, cellIndex: IndexPath, tableTag: Int) {
        print("1--->>",sender)
    }
    
    func circularClick(sender: UITapGestureRecognizer, cellIndex: IndexPath, tableTag: Int) {
//        print("2--->>",sender)
        
        // 蓝牙写这里
        self.blueWrite()
        
    }
    
    func dropDownClick(sender: UIButton, cellIndex: IndexPath, tableTag: Int) {
        HMPickerView.sharePicker.sign = "\(sender.tag)"
        HMPickerView.creatorDate()
        HMPickerView.sharePicker.setDateRange(max: [0,0,0], min: [-1,0,0])
        HMPickerView.sharePicker.setPickerMode(.dateAndTime)  // =  time
        HMPickerView.sharePicker.returnDatePicker = {
            (datePicker) -> () in
            let formatter = DateFormatter()
            //日期样式
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            let itemAry =  self.rightAry!
            let str = formatter.string(from: datePicker.date)
            
            let dic = itemAry[cellIndex.row] as! NSDictionary
            dic.setValue(str, forKey: "value")
            
             self.rigthTableView.reloadRows(at: [cellIndex], with: UITableViewRowAnimation.none)
            let  cell = self.rigthTableView.cellForRow(at: cellIndex) as! MultiFunctionCell
               cell.MFC_DropDown?.setTitle(str, for: UIControlState.normal)
        }
    }
    
  func radioClick(sender: UIButton, cellIndex: IndexPath, tableTag: Int) {
    
        let itemAry =  self.rightAry!
        let dic = itemAry[cellIndex.row] as! NSDictionary
        let item = dic["title"] as! NSArray
    
        let  str  = item[sender.tag] as! String
        dic.setValue(str, forKey: "value")
    
        // 获取类型 - 比如血压下的内容
    }
    
    
}



extension Device {
    /// 获取存储文件 路径
    func createPlistFile(fileName: String) -> String{
        //
        let plistPath: String? = Bundle.main.path(forResource: fileName, ofType: "plist")!
        return plistPath!
    }
    func getPlistArray(fileName: String) -> NSMutableArray {
        let  plistPath = self.createPlistFile(fileName: fileName)
        let resultAry = NSMutableArray.init(contentsOfFile: plistPath)
        return resultAry!
    }
    func writePlistFile(fileName: String, writeAry: NSMutableArray) {
           let  plistPath = self.createPlistFile(fileName: fileName)
//           let resultAry = self.getPlistArray(fileName: fileName)
            writeAry.write(toFile: plistPath, atomically: true)
    }
    
    
    /// 自动写入
    func blueWrite() {
        
         //"DeviceTestData"
         let itemAry =  self.rightAry!  //self.getPlistArray(fileName: "DeviceTestData")
        
         // 获取类型 - 比如血压下的内容
        
        
        var i = 0
        for item in itemAry {
             let  dic = item as! NSDictionary
              let type = dic["type"] as! String
            if type != "button" && type != "circular" {
               print("\(dic)--------YTY")
                
//                let value = dic["value"] as! String
                dic.setValue("打工\(i)", forKey: "value")
                
            }else {
               print("======YTY\(dic)")
            }
            
            
            i += 1
        }
        self.rigthTableView.reloadData()
    }
    
}


//CBPeripheralManagerDelegate 外设  -- CBCentralManagerDelegate 中心设备
extension  Device: CBCentralManagerDelegate, CBPeripheralDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("未知类型")
        case .resetting:
            print("重置中")
        case .unsupported:
            print("不支持")
        case .unauthorized:
            print("未验证")
        case .poweredOff:
            print("未启用")
        case .poweredOn:
            print("可用")
            
            // 创建服务 和 特征
           // setupServiceAndCharacteristics()
            // 根据服务的UUID 开始广播
            //        self.peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [CBUUID.init(string: Service_UUID)]]) // 链接？
            let service_UUID = "///"
            central.scanForPeripherals(withServices: [CBUUID.init(string: service_UUID)], options: nil)
        }
    }
    /** 连接成功 */
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        self.centralManager?.stopScan()
        peripheral.delegate = self
        let service_UUID = "///"
        peripheral.discoverServices([CBUUID.init(string: service_UUID)])
        print("连接成功")
    }
    /** 连接失败的回调 */
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("连接失败")
    }
    /** 断开连接 */
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("断开连接")
        // 重新连接
        central.connect(peripheral, options: nil)
    }
    
    /** 发现服务 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service: CBService in peripheral.services! {
            print("外设中的服务有：\(service)")
        }
        //本例的外设中只有一个服务
        let service = peripheral.services?.last
        // 根据UUID寻找服务中的特征
        //peripheral.discoverCharacteristics([CBUUID.init(string: Characteristic_UUID)], for: service!)
    }
    /** 发现特征 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        for characteristic: CBCharacteristic in service.characteristics! {
            print("外设中的特征有：\(characteristic)")
        }
        
        self.characteristic = service.characteristics?.last
        // 读取特征里的数据
        peripheral.readValue(for: self.characteristic!)
        // 订阅
        peripheral.setNotifyValue(true, for: self.characteristic!)
    }
    
    /** 订阅状态 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            print("订阅失败: \(error)")
            return
        }
        if characteristic.isNotifying {
            print("订阅成功")
        } else {
            print("取消订阅")
        }
    }
    
    /** 接收到数据 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
//        let data = characteristic.value
//        self.textField.text = String.init(data: data!, encoding: String.Encoding.utf8)
    }
    
//    @IBAction func didClickPost(_ sender: Any) {
//        let data = (self.textField.text ?? "empty input")!.data(using: String.Encoding.utf8)
//        self.peripheral?.writeValue(data!, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
//    }
//    6
//    /** 写入数据 */
//    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
//        print("写入数据")
//    }
    
   
    
}


